import Vue from 'vue';
import VueRouter from 'vue-router';
import {isWechat, wechatReady, wechatConfig} from '@/lib/wechat.js';
import routes from './pathConfig';
import util from '../lib/util';

Vue.use(VueRouter);

const createRouter = () => {

  const router = new VueRouter({
    routes: routes,
    scrollBehavior(to, from, savedPosition) {

      if (savedPosition) {
        return savedPosition
      } else {
        return {x: 0, y: 0}
      }
    }
  });
  router.beforeEach((to, from, next) => {

    const prefixUrl = window.location.href.split('#')[0];
    const url = `${prefixUrl}#${to.fullPath}`;
    // 判断是否为微信浏览器
    // if (isWechat()) {
    // }
    wechatConfig(url)
    // 把自定义配置分享内容传递进去
    if (to.meta.wechatLink) {
      wechatReady(Object.assign({}, to.meta));
    } else {
      wechatReady(Object.assign({}, to.meta, { link: url }));
    }
    // 修改页面title
    if (to.meta.title) {
      document.title = to.meta.title;
    }
    next();
    util.vars.inTime = new Date().getTime();
  });
  router.afterEach((to, from) => {
    // 页面添加数据埋点
    if (from.meta.page_type) {

      util.ajax.post('/stat/pageAndButton', util.jsonStringify({
        action_type: 1,
        page_type: from.meta.page_type,
        in_time: util.vars.inTime,
        out_time: new Date().getTime(),
        extra: from.query.id || ''
      })).then(res => {/*todu*/
      });
    }

  });
  return router;
};

export default createRouter();
